﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.UserCommand;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.UserCommandHandler
{
    /// <summary>
    /// 修改用户表
    /// </summary>
    public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userrReppos;
        private readonly IMapper mapper;

        public UpdateUserCommandHandler(IBaseRepository<User> userrReppos, IMapper mapper)
        {
            this.userrReppos = userrReppos;
            this.mapper = mapper;
        }

        public Task<APIResult<object>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var getObj = userrReppos.GetAll().Result.FirstOrDefault(x => x.UserId == request.UserId);
            getObj.UserName = request.UserName;
            getObj.Sex = request.Sex;
            getObj.ProvinceId = request.ProvinceId;
            getObj.CityId = request.CityId;
            getObj.CountyId = request.CountyId;
            getObj.HamletName = request.HamletName;
            getObj.UpdateName = request.UpdateName;
            getObj.UpdateTime = DateTime.Now;
            //var model = mapper.Map<User>(request);
            var obj = userrReppos.Update(getObj).Result;
            if (obj > 0)
            {
                result.Code = APIEnum.修改成功;
                result.Msg = APIEnum.修改成功.ToString();
                result.data = obj;
            }
            else
            {
                result.Code = APIEnum.修改失败;
                result.Msg = APIEnum.修改失败.ToString();
            }

            return Task.FromResult(result);
        }
    }
}
